import Snap from 'snapsvg-cjs'
import palletUri from '@/assets/svg/Pallet.svg'// 托盘Svg地址
import tooltipUri from '@/assets/svg/device_comment.svg'// 提示框Svg地址
import mainSvgUri from '@/assets/svg/sdtek.svg'// 项目布局Svg地址
import { zpd } from 'snap.svg.zpd'
import * as SvgConfig from './SvgConfig.js'
import * as SvgColor from './changeColor.js'

const hoverTimeout = 500
let vue = null
let svg = null
let group = null
let paper = null
let pallet = null
let tooltip = null
let currentHover = ''
let currentHoverEnd = false
let isComlpeted = false
let singalRData = null
let currentTips = null
let devices = {
  con: [],
  srm: [],
  bcr: [],
  rgv: [],
  other: [],
  box: [],
  srmLength: [],
  raster: [],
  tsj: [],
  TSJ: []
}
/** 清除数据 */
export function clear() {
  devices = {
    con: [],
    srm: [],
    bcr: [],
    rgv: [],
    other: [],
    box: [],
    srmLength: [],
    raster: [],
    tsj: [],
    TSJ: []
  }
}
/** 初始化Svg */
export function InitSvg(value) {
  vue = value
  svg = Snap('#svg')
  svg.zpd('destroy')
  svg.zpd()
  group = svg.select('g')

  SvgConfig.SetSvgStyle()

  Snap.load(mainSvgUri, (data) => group.append(data.select('svg')))
  Snap.load(tooltipUri, (data) => {
    tooltip = data.select('g')
    group.select('svg').append(tooltip)
  })

  setTimeout(() => {
    Snap.load(palletUri, (data) => {
      pallet = data.select('g')
      group.select('svg').append(pallet)
    })
  }, 500)

  setTimeout(() => {
    // console.log(pallet, 'wwww')
    InitDevices()
  }, 500)
}
/** 处理SingalR数据推送 */
export function HandleSingalRData(value) {
  console.log(value)
  vue.tableData = [value.currentTask]
  vue.controlModel.PLCStatus = value.heartBeatInfo.connectState
  vue.controlModel.MCSSTatus = value.mcsConnectStatus
  vue.controlModel.Ver = value.softrev
  // console.log(vue.controlModel)
  SetSingalRData(value)
  if (isComlpeted) {
    HandleConChanged()
    HandleSrmChanged()
    HandleRasterChanged()
    HandleRgvChanged()
    HandleModeChanged()
    HandletsjChanged()
  }
}
/** 获取推送的数据 */
export function getsingalRData() {
  return singalRData
}
/** 配置设备 */
function InitDevices() {
  paper = group.paper
  const sets = paper.selectAll('*')
  sets.forEach((el) => {
    const name = el.node.id
    if (name.indexOf('mode') > -1) SetModeDevice(el, name)
    if (name.indexOf('con') > -1) SetConDevice(el, name)
    if (name.indexOf('srm') > -1) SetSrmDevice(el, name)
    if (name.indexOf('bcr') > -1) SetBcrDevice(el, name)
    if (name.indexOf('rgv') > -1) SetRgvDevice(el, name)
    if (name.indexOf('trail') > -1) SetSrmTrail(el, name)
    if (name.indexOf('shelf') > -1) SetSrmThelf(el, name)
    if (name.indexOf('raster') > -1) SetRasterDevice(el, name)
    if (name.indexOf('tsj') > -1) SettsjDevice(el, name)
    if (name.indexOf('TSJ') > -1) {
      devices.TSJ.push(el)
    }
  })
  isComlpeted = true
}
/** 设置Srm路径长度 */
function SetSrmTrail(el, name) {
  const width = el.node.width.baseVal.value
  const height = el.node.height.baseVal.value
  devices.srmLength.push({
    name,
    length: width > height ? width : height
  })
}
/** 设置bcr设备 光栅 */
function SetBcrDevice(el, name) {
  // devices.bcr.push(el)
  // el.click(function() {
  //   BcrClick(name)
  // })
}
/** 设置Srm设备 */
function SetSrmDevice(el, name) {
  devices.srm.push(el)
  el.click(function() {
    SrmClick(name)
  })
  // el.hover(
  //   function () {
  //     DeviceHover(name, 'srm', el)
  //   },
  //   function () {
  //     DeviceHoverOff()
  //   }
  // )
}
/** 设置Rgv设备 */
function SetRgvDevice(el, name) {
  devices.rgv.push(el)
  el.click(function() {
    RgvClick(name)
  })
}
/** 设置输送线设备 */
function SetConDevice(el, name) {
  devices.con.push(el)
  el.click(function() {
    ConClick(name)
  })
  el.hover(
    function() {
      DeviceHover(name, 'con', el)
    },
    function() {
      DeviceHoverOff()
    }
  )
  CreateSvgText(paper, name, 82, el)
}
/** 设置提升机设备 */
function SettsjDevice(el, name) {
  devices.tsj.push(el)
  el.click(function() {
    tsjClick(name)
  })
  // CreateSvgText(paper, name, 42, el)
}
/** 设置光栅 raster设备 */
function SetRasterDevice(el, name) {
  devices.raster.push(el)
  el.click(function() {
    RasterClick(name)
  })
}
/** 悬停 */
function DeviceHover(name, type, el) {
  if (!isComlpeted) return
  const hoverFlag = name
  currentHover = hoverFlag
  currentHoverEnd = true
  const tipsEl = group.select(`#hover-tips`)
  if (tipsEl !== null) tipsEl.remove()
  setTimeout(() => {
    if (currentHover === hoverFlag && currentHoverEnd) {
      try {
        console.log(tooltip, 'tooltip')
        currentTips = tooltip
          .clone()
          .attr({ id: 'hover-tips', display: 'block' })
      } catch (error) {
        return
      }
      SetTooltip(el, type)
    }
  }, hoverTimeout)
}
/** 解除悬停 */
function DeviceHoverOff() {
  if (!isComlpeted) return
  currentHoverEnd = false
  if (currentTips !== null) {
    currentTips.remove()
    currentTips = null
  }
}
/** 设置悬浮弹窗内容 */
function SetTooltip(el, type) {
  console.log(el, 'el', type)
  const sets = currentTips.selectAll('*')
  const posi = SvgConfig.GetElementRightTop(el)
  sets.forEach(function(el, index) {
    const type = el.type
    if (type === 'path') {
      el.attr({
        d: `M${posi.x},${posi.y} h1200 v450 h-950 L${posi.x + 250
        },${posi.y + 150} z`
      })
    } else if (type === 'text') {
      el.attr({
        x: posi.x + 300,
        y: posi.y + index * 100
      })
    }
  })
  let currentData = null
  if (type === 'con') {
    currentData = singalRData.con.find(
      (item) => ('con' + item.name) === el.node.id
    )
  } else if (type === 'srm') {
    currentData = singalRData.srm.find(
      (item) => item.name === el.node.id
    )
  }
  if (!(currentData === undefined || currentData === null)) {
    sets[1].node.innerHTML += currentData.des
    sets[2].node.innerHTML += currentData.unitId
    sets[3].node.innerHTML += SvgConfig.GetModeMappingData(currentData.pconMode)
  }
}
/** 设置模式灯，存储 */
function SetModeDevice(el, name) {
  devices.other.push(el)
  el.click(function() {
    // let singalRData = getsingalRData()
    const newdata = singalRData.other.find(item => item.name === name)
    vue.IOPortData = newdata
    SetDialogProperty(name, false)
  })
}
/** 设置货架 */
function SetSrmThelf(el, name) {
  // devices.srm.push(el)
  el.click(function() {
    vue.thelfDialog = true
  })
}

/** 创建SVG   Text
 * @param {*} paper SVG paper
 * @param {*} name text内容
 * @param {*} size 字体大小
 * @param {*} el 在目标元素上显示
 */
function CreateSvgText(paper, name, size, el) {
  var textSplit
  // 将获取到的text内容去除con
  if ((name.indexOf('con') > -1)) {
    textSplit = name.replace('con', '')
  }
  if ((name.indexOf('srm') > -1)) {
    textSplit = name.replace('con', '')
  }
  const t = paper.text(0, 0, textSplit).attr({
    fill: '#fff',
    'font-size': size,
    x: el.node.x.baseVal.value + 5,
    y: el.node.y.baseVal.value + size
  })
  t.insertAfter(el)
}

/** 设置SingalR的数据 */
function SetSingalRData(value) {
  singalRData = {
    con: value.pcons,
    srm: value.lifts,
    // rgv: value.monitorConDatas,
    other: value.monitorOtherDatas,
    raster: value.rasters
  }
  // console.log(value, singalRData)
}
/** 处理Con数据变化 */
function HandleConChanged() {
  singalRData.con.forEach((data) => {
    const dev = devices.con.find((item) => item.node.id === ('con' + data.deviceName))
    // console.log(data)
    if (vue.conDialog) {
      if ((data.deviceName) === vue.dialogTitle) {
        vue.particularsData = data
      }
    }
    const dev_g = group.select(`#g-${data.deviceName}`)
    if (dev) {
      const color = SvgColor.GetCvRgvTsjModeColor(data.pconMode)
      const box = group.select(`#box-${data.deviceName}`)
      if (data.unitId !== null && data.unitId !== '' && data.isGoods === true) {
        box.attr({ 'display': 'block' })
      } else {
        box.attr({ 'display': 'none' })
      }
      const light_in = document.getElementById(`${data.deviceName}-light-in`)
      const light_out = document.getElementById(`${data.deviceName}-light-out`)
      // if (light_in && light_out) {
      //   if (data.workType === '入库模式') {
      //     light_in.setAttribute('display', 'block')
      //     light_out.setAttribute('display', 'none')
      //     light_in.setAttribute('fill', '#FFFF00')
      //     light_out.setAttribute('fill', '#FFFF00')
      //   } else if (data.workType === '出库模式') {
      //     light_in.setAttribute('display', 'none')
      //     light_out.setAttribute('display', 'block')
      //     light_in.setAttribute('fill', '#FFFF00')
      //     light_out.setAttribute('fill', '#FFFF00')
      //   } else if (data.workType === '双向模式') {
      //     light_in.setAttribute('display', 'block')
      //     light_out.setAttribute('display', 'block')
      //     light_in.setAttribute('fill', '#FFFF00')
      //     light_out.setAttribute('fill', '#FFFF00')
      //   } else if (data.workType === '人工投料') {
      //     light_in.setAttribute('display', 'block')
      //     light_in.setAttribute('fill', 'skyblue')
      //     light_out.setAttribute('display', 'block')
      //     light_out.setAttribute('fill', 'skyblue')
      //   } else {
      //     light_in.setAttribute('display', 'none')
      //     light_in.setAttribute('fill', '#FFFF00')
      //     light_out.setAttribute('display', 'none')
      //     light_out.setAttribute('fill', '#FFFF00')
      //   }
      // }
      // SvgConfig.DoColorAnimate(dev, color)
      dev.node.setAttribute('fill', color)
    } else {
      // console.log(`error,未找到${data.deviceName}`)
    }
  })
}
/** 处理Srm数据变化 */
function HandleSrmChanged() {
  // console.log('HandleSrmChanged');
  singalRData.srm.forEach((data) => {
    // console.log(data)
    const dev = devices.srm.find((item) => item.node.id === ('srm' + data.deviceName))
    if (vue.srmDialog) {
      if ((data.deviceName) === vue.dialogTitle) {
        vue.particularsData = data
      }
    }
    const dev_g = group.select(`#g-${data.deviceName}`)
    const dev_bcr = group.select(`#bcr-${data.deviceName}`)
    if (dev_g) {
      const color = SvgColor.GetModeColor(data.deviceMode)
      const matrix = GetTrailPosition(data.currentBay, ('srm' + data.deviceName)) // 获取轨道位置
      const box = group.select(`#box-${data.deviceName}`)
      if (data.unitId !== null && data.unitId !== '' && data.isGoods === 1) {
        box.attr({ 'display': 'block' })
      } else {
        box.attr({ 'display': 'none' })
      }
      if (data.bcrState === 0) {
        dev_bcr.node.setAttribute('fill', '#999')
      } else {
        dev_bcr.node.setAttribute('fill', '#00FF00')
      }
      SvgConfig.DoPositionAnimate(dev_g, matrix)
      dev.node.setAttribute('fill', color)
    } else {
      console.log(`error,未找到${data.deviceName}`)
    }
  })
}

/** 处理tsj数据变化 */
function HandletsjChanged() {
  singalRData.con.forEach((data) => {
    const dev = devices.tsj.find((item) => item.node.id === ('tsj' + data.name))
    if (vue.tsjDialog) {
      if ((data.name) === vue.dialogTitle) {
        vue.particularsData = data
      }
    }
    const dev_g = group.select(`#g-${data.name}TSJ`)
    if (dev) {
      const color = SvgColor.GetCvRgvTsjModeColor(data.pconMode)
      const matrix = GetTrailPosition(data.devLoc, data.name) // 获取轨道位置
      const box = group.select(`#box-${data.name}TSJ`)
      if (data.unitId !== null && data.unitId !== '' && data.isGoods === 1) {
        box.attr({ 'display': 'block' })
      } else {
        box.attr({ 'display': 'none' })
      }
      SvgConfig.DoPositionAnimate(dev_g, matrix)
      SvgConfig.DoColorAnimate(dev, color)
    } else {
      // console.log(`error,未找到${data.name}`)
    }
  })
}
/** 处理Rgv数据变化 */
function HandleRgvChanged() {
  singalRData.con.forEach((data) => {
    const dev = devices.rgv.find((item) => item.node.id === ('rgv' + data.name))
    if (vue.rgvDialog) {
      if ((data.name) === vue.dialogTitle) {
        vue.particularsData = data
      }
    }
    const dev_g = group.select(`#g-rgv${data.name}`)
    if (dev) {
      const color = SvgColor.GetCvRgvTsjModeColor(data.pconMode)
      const matrix = GetTrailPosition(data.devLoc, data.name) // 获取轨道位置
      const box = group.select(`#box-rgv${data.name}`)
      if (data.unitId !== null && data.unitId !== '' && data.isGoods === 1) {
        box.attr({ 'display': 'block' })
      } else {
        box.attr({ 'display': 'none' })
      }
      SvgConfig.DoPositionAnimate(dev_g, matrix)
      dev.node.setAttribute('fill', color)
    } else {
      // console.log(`error,未找到${data.name}`)
    }
  })
}
/** 处理 raster 数据变化 */
function HandleRasterChanged() {
  // console.log('HandleRasterChanged', singalRData, devices.raster)
  singalRData.raster.forEach((data) => {
    const dev = devices.raster.find((item) => item.node.id === data.name)
    if (vue.raster) {
      if (data.name === vue.dialogTitle) {
        vue.particularsData = data
      }
    }

    if (dev) {
      if (data.errorFlag) {
        dev.node.setAttribute('fill', SvgColor.rasterColor.errorFlag)
      } else if (data.bypassFlag) {
        dev.node.setAttribute('fill', SvgColor.rasterColor.bypassFlag)
      } else {
        dev.node.setAttribute('fill', SvgColor.rasterColor.default)
      }
    } else {
      console.log(`error,未找到${data.name}`)
    }
  })
}
/** 处理Mode数据变化 */
function HandleModeChanged() {
  singalRData.other.forEach((data) => {
    const dev = devices.other.find((item) => item.node.id === data.name)
    const color = data.mode ? '#67C23A' : '#F56C6C'
    dev.node.setAttribute('fill', color)
  })
}
/** 获取堆垛机当前所在位置 */
function GetTrailPosition(bayNum, srmName) {
  // let srmTrailName
  let length
  const matrix = new Snap.Matrix(1, 0, 0, 1, 0, 0)
  if (srmName.indexOf('srmCJSTW100') > -1) {
    if (bayNum > 42) bayNum = 42
    length = 4900 // 4900
    let p = bayNum / 42 * length
    if (bayNum === 25) {
      p += 75
    }
    matrix.add(1, 0, 0, 1, 0, -p)
    return matrix
  } else if (srmName.indexOf('srmCJSTW200') > -1) {
    if (bayNum > 59) bayNum = 59
    length = 6250 // 6250
    const p = bayNum / 59 * length
    matrix.add(1, 0, 0, 1, 0, -p)
    return matrix
  } else if (srmName.indexOf('CJRGV200-C1') > -1) {
    length = 2300
    let p = 0
    if (bayNum < 3834) bayNum = 3834
    if (bayNum > 38994) bayNum = 38994
    p = ((bayNum - 3834) / 35160) * length
    if (bayNum < 3834) p = 0
    matrix.add(1, 0, 0, 1, 0, -p)
    return matrix
  } else if (srmName.indexOf('CJRGV100-C1') > -1) {
    length = 7000
    if (bayNum < 5935) bayNum = 5935
    if (bayNum > 110190) bayNum = 110190
    const p = ((1 - ((bayNum - 5935) / 104255))) * length
    matrix.add(1, 0, 0, 1, 0, p)
    return matrix
  } else if (srmName.indexOf('CJRGV100-C2') > -1) {
    length = 7000
    let p = 0
    if (bayNum < 5935) bayNum = 5935
    if (bayNum > 110190) bayNum = 110190
    p = ((bayNum - 5935) / 104255) * length
    matrix.add(1, 0, 0, 1, 0, -p)
    return matrix
  } else if (srmName.indexOf('CJMIFB00') > -1 || srmName.indexOf('CJMIFC00') > -1) {
    length = 100
    let p
    if (bayNum === 1) {
      p = 0
    } else if (bayNum === 2) {
      p = bayNum * length
    } else if (bayNum === 3) {
      p = (bayNum + 4) * length
    }
    matrix.add(1, 0, 0, 1, 0, -p)
    return matrix
  }
}
/** 添加货物（托盘）
 * @param {*} boxName Svg标签托盘ID
 * @param {*} el 设备Svg
 */
function AddGoods(boxName, el) {
  const box = GetBox(boxName, el)
  box.attr({ display: 'block' })
}
/** 移除货物
 * @param {*} boxName 货物Id
 */
function RemoveGoods(boxName) {
  const box = document.getElementById(boxName)
  if (box !== undefined && box !== null) {
    box.style.display = 'none'
  }
}
/** 获取货物图形
 * @param {*} boxName
 * @param {*} el 设备Element
 * @returns box
 */
function GetBox(boxName, el) {
  let box = group.select(`#${boxName}`)
  if (box === undefined || box === null) {
    box = pallet.clone().attr({ id: boxName, display: 'block' })
    const appearance = SvgConfig.GetDeviceAppearance(el)
    const subbox = box.selectAll('*')
    subbox[0].attr({
      x: appearance.pos.x + 10,
      y: appearance.pos.y + 10,
      width: appearance.size,
      height: appearance.size
    })
    subbox[1].attr({
      x: appearance.pos.x,
      y: appearance.pos.y,
      width: appearance.size,
      height: appearance.size
    })
  }
  return box
}
/** 输送设备点击 */
function ConClick(name) {
  const dev = singalRData.con.find(item => ('con' + item.deviceName) === name)
  console.log(name)
  if (dev) {
    vue.particularsData = dev
    vue.dialogTitle = dev.machineName + '-' + dev.portName + '(' + dev.deviceName + ')'
  } else {
    vue.particularsData = {}
  }
  vue.conDialog = true
}
/** 堆垛机设备点击 */
function SrmClick(name) {
  const nowsrm = singalRData.srm.find((item) => ('srm' + item.deviceName) === name)
  console.log(nowsrm, 'nowsrm', singalRData.srm, name)
  if (nowsrm) {
    vue.particularsData = nowsrm
    vue.errorCode = nowsrm.errorCode
    vue.dialogTitle = nowsrm.machineName
  } else {
    vue.particularsData = {}
  }
  vue.srmDialog = true
}
/** 光栅Raster设备点击 */
function RasterClick(name) {
  // SetDialogProperty(name, 'raster', false)
  const dev = singalRData.raster.find(item => item.name === name)
  console.log(dev)
  if (dev) {
    vue.particularsData = dev
    // console.log(vue.particularsData);
  } else {
    vue.particularsData = {}
  }
  vue.rasterDialog = true
  vue.dialogTitle = name
}
// 提升机设备点击
function tsjClick(name) {
  name = name.replace('tsj', '')
  vue.tsjDialog = true
  vue.dialogTitle = name
  const nowtcl = singalRData.con.find((item) => item.name === name)
  // console.log(nowtcl, 'nowtcl', singalRData.con, name)
  if (nowtcl) {
    vue.particularsData = nowtcl
    // console.log(vue.particularsData);
  } else {
    vue.particularsData = {}
  }
}
// bcr设备点击 光栅
function BcrClick(name) {
  vue.bcrDialog = true
  vue.dialogTitle = name
}

/** rgv设备点击 */
function RgvClick(name) {
  // SetDialogProperty(name.replace('rgv', ''), 1, false)
  // vue.disableClickShow = true
  name = name.replace('g-rgv', '')
  vue.rgvDialog = true
  vue.dialogTitle = name
  const nowrgv = singalRData.con.find((item) => item.name === name)
  console.log(nowrgv, 'nowrgv')
  if (nowrgv) {
    vue.particularsData = nowrgv
    console.log(vue.particularsData)
    vue.errorCode = nowrgv.errorCode
  } else {
    vue.particularsData = {}
  }
}
/** 设置Dialog属性 */
function SetDialogProperty(name, option) {
  vue.particularsclick = false
  vue.errorCode = 0
  vue.conDialog = true
  vue.dialogTitle = name
  vue.dialogOption = option
}

